import { message } from 'antd';
import {
  getRoleList,
  getOrgRoleList,
  deleteRole,
  addRole,
  addOrgRole,
  updateRole,
  updateOrgRole,
  getMenuTreeData,
  getRoleUserList,
  getOrgList,
} from '../services';

export default {
  namespace: 'orgRoleManageModel',
  state: {
    // value: 123,
    roleList: [],
    roleListTotal: 0,
  },
  effects: {
    *getRoleList({ payload }, { put, call, select }) {
      const res = yield call(getRoleList, payload);
      const { code, data, message: errMsg } = res;
      if (code === 0 && data) {
        const { dataList, total } = data;
        yield put({
          type: 'updateModel',
          payload: {
            roleList: dataList.map((d) => ({ ...d, orgs: d.orgList?.filter(Boolean)?.map((r) => r.orgName)?.join(',') })),
            roleListTotal: total,
          },
        });
      } else {
        message.error(errMsg);
      }
    },
    *getOrgRoleList({ payload }, { put, call, select }) {
      const res = yield call(getOrgRoleList, payload);
      const { code, data, message: errMsg } = res;
      if (code === 0 && data) {
        const { dataList, total } = data;
        yield put({
          type: 'updateModel',
          payload: {
            roleList: dataList.map((d) => ({ ...d, orgs: d.orgList?.filter(Boolean)?.map((r) => r.orgName)?.join(',') })),
            roleListTotal: total,
          },
        });
      } else {
        message.error(errMsg);
      }
    },
    *getAllRoleList({ payload }, { put, call, select }) {
      return yield call(getRoleList, payload);
    },
    *getAllOrgList({ payload }, { put, call, select }) {
      return yield call(getOrgList, payload);
    },
    *addRole({ payload }, { put, call, select }) {
      return yield call(addRole, payload);
    },
    *addOrgRole({ payload }, { put, call, select }) {
      return yield call(addOrgRole, payload);
    },

    *updateRole({ payload }, { put, call, select }) {
      return yield call(updateRole, payload);
    },
    *updateOrgRole({ payload }, { put, call, select }) {
      return yield call(updateOrgRole, payload);
    },

    *deleteRole({ payload }, { put, call, select }) {
      return yield call(deleteRole, payload);
    },
    *getMenuTreeData({ payload }, { put, call, select }) {
      return yield call(getMenuTreeData, payload);
    },
    *getRoleUserList({ payload }, { put, call, select }) {
      return yield call(getRoleUserList, payload);
    },
  },
  reducers: {
    /* 更新状态（通用） */
    updateModel: (state, { payload }) => ({
      ...state,
      ...payload,
    }),
  },
};
